#!/usr/bin/env node

/**
 * Quick test script to verify HTTP server functionality
 */

import axios from 'axios';

const BASE_URL = 'http://localhost:3000';

async function testHttpServer() {
  console.log('🧪 Testing Java Decompiler HTTP Server...\n');

  try {
    // Test 1: Health check
    console.log('1. Testing health check...');
    const health = await axios.get(`${BASE_URL}/health`);
    console.log('   ✅ Health check passed:', health.data.status);
    
    // Test 2: API info
    console.log('\n2. Testing API info...');
    const info = await axios.get(`${BASE_URL}/api/info`);
    console.log('   ✅ API info retrieved:', info.data.name);
    console.log('   📋 Available endpoints:', info.data.endpoints.length);
    
    // Test 3: Search artifacts
    console.log('\n3. Testing artifact search...');
    const searchResult = await axios.post(`${BASE_URL}/api/search-artifacts`, {
      query: 'commons-lang3'
    });
    console.log(`   ✅ Search completed, found ${searchResult.data.found} artifacts`);
    
    if (searchResult.data.artifacts.length > 0) {
      const firstArtifact = searchResult.data.artifacts[0];
      console.log(`   📦 First artifact: ${firstArtifact.groupId}:${firstArtifact.artifactId}:${firstArtifact.version}`);
      
      // Test 4: Download artifact
      console.log('\n4. Testing artifact download...');
      const downloadResult = await axios.post(`${BASE_URL}/api/download-artifact`, {
        groupId: firstArtifact.groupId,
        artifactId: firstArtifact.artifactId,
        version: firstArtifact.version
      });
      
      if (downloadResult.data.success) {
        console.log(`   ✅ Download successful, found ${downloadResult.data.classCount} classes`);
        
        if (downloadResult.data.classes.length > 0) {
          // Test 5: Search classes
          console.log('\n5. Testing class search...');
          const classSearch = await axios.post(`${BASE_URL}/api/search-classes`, {
            query: 'String'
          });
          
          if (classSearch.data.totalMatches > 0) {
            console.log(`   ✅ Class search successful, found ${classSearch.data.totalMatches} matches`);
            
            const firstClass = classSearch.data.matches[0];
            console.log(`   🔍 First match: ${firstClass.fullName}`);
            
            // Test 6: Decompile class (optional, might be slow)
            console.log('\n6. Testing class decompilation...');
            try {
              const decompileResult = await axios.post(`${BASE_URL}/api/decompile-class`, {
                groupId: firstClass.artifact.groupId,
                artifactId: firstClass.artifact.artifactId,
                version: firstClass.artifact.version,
                className: firstClass.fullName
              }, { timeout: 30000 });
              
              if (decompileResult.data.success) {
                console.log(`   ✅ Decompilation successful for ${decompileResult.data.className}`);
                console.log(`   📄 Source code length: ${decompileResult.data.source.length} characters`);
              } else {
                console.log(`   ⚠️ Decompilation failed: ${decompileResult.data.error}`);
              }
            } catch (decompileError) {
              console.log(`   ⚠️ Decompilation test skipped: ${decompileError.message}`);
            }
          } else {
            console.log('   ⚠️ No classes found matching "String"');
          }
        } else {
          console.log('   ⚠️ No classes found in downloaded artifact');
        }
      } else {
        console.log(`   ❌ Download failed: ${downloadResult.data.error}`);
      }
    } else {
      console.log('   ⚠️ No artifacts found for "commons-lang3"');
    }
    
    console.log('\n🎉 HTTP server test completed successfully!');
    console.log('\n💡 Try the example clients:');
    console.log('   node examples/http-client-example.js');
    console.log('   python3 examples/http-client-example.py');
    
  } catch (error) {
    console.error('\n❌ HTTP server test failed:', error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.error('\n💡 Make sure the HTTP server is running:');
      console.error('   npm run dev:http');
      console.error('   # or');
      console.error('   npm run build && npm run start:http');
    }
    
    process.exit(1);
  }
}

testHttpServer();